<template>
  <el-form
    :model="editCustomerData"
    v-loading="loading"
    label-position="left"
    size="small"
    :rules="rules"
    ref="form"
    label-width="150px"
    class="project-form"
  >
    <h4 class="form-title">基本信息</h4>
    <el-form-item label="组织类型" prop="org_class">
      <select-customer-type
        class="form-control-ml"
        v-model="editCustomerData.org_class"
        :is-gua="true"
        @select="handleOrgClassSelect"
      ></select-customer-type>
    </el-form-item>

    <el-form-item
      label="营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)"
      v-show="isCommon"
    >
      <upload-oss
        single-image
        :dir="dir"
        ref="uploadRegister"
        accept="image/*"
        :file-name="0"
        :file-list="registerList"
        :on-change="registerChange"
        :on-complete="handleUploadRegister"
      ></upload-oss>
    </el-form-item>

    <el-form-item label="身份证照片OCR识别(请上传清晰的图片，以确保识别准确性，非必填)">
      <ul class="list-inline">
        <li class="list-inline-item">
          <upload-oss
            single-image
            :dir="dir"
            ref="uploadFront"
            accept="image/*"
            :file-name="0"
            :file-list="idImgFront"
            :on-change="idImgFrontChange"
            :on-complete="handleUploadFront"
          ></upload-oss>
          <div class="text-muted text-center">身份证头像页</div>
        </li>
        <li class="list-inline-item">
          <upload-oss
            single-image
            :dir="dir"
            ref="uploadBack"
            accept="image/*"
            :file-list="idImgBack"
            :on-complete="handleUploadBack"
          ></upload-oss>
          <div class="text-muted text-center">身份证国徽页</div>
        </li>
      </ul>
    </el-form-item>

    <el-form-item label="客户名称" prop="customer_name">
      <el-autocomplete
        v-model="editCustomerData.customer_name"
        class="form-control-ml"
        placeholder="请输入客户名称"
        popper-class="customer-autocomplete"
        value-key="customer_name"
        :fetch-suggestions="throttleGetData"
        @input="clearId"
        @select="handleSelectFarm"
      >
        <template slot-scope="props">
          <div class="farm-name">{{ props.item.customer_name || '' }}</div>
          <small class="text-muted">
            {{ (props.item.address || '') + (props.item.address_detail || '') }}
          </small>
        </template>
      </el-autocomplete>
    </el-form-item>
    <el-form-item :label="isCommon ? '经营地址' : '家庭地址'" prop="address_code">
      <select-address
        class="form-control-ml"
        @select="getAddress"
        clearable
        v-model="editCustomerData.address_code"
        auto-top
      ></select-address>
    </el-form-item>
    <el-form-item label="详细地址(街道、门牌)">
      <el-input
        v-model="editCustomerData.address_detail"
        class="form-control-ml"
        placeholder="请勿重复输入已选地址（对已选地址的补充说明）"
      ></el-input>
      <div class="text-warning small form-control-ml" style="line-height: 1.2">
        请勿重复输入已选地址,当前地址：
        {{
          addressLabel
            ? topAddressLabel + addressLabel + editCustomerData.address_detail
            : tableData.address
        }}
      </div>
    </el-form-item>

    <el-form-item label="营业执照号" v-if="isCommon" prop="register_no">
      <el-input
        v-model="editCustomerData.register_no"
        class="form-control-ml"
        placeholder="营业执照号"
      >
        <el-button slot="append" class="input-group-text" type="info" @click="linkto">
          工商信息
        </el-button>
      </el-input>
    </el-form-item>
    <el-form-item label="成立日期" v-if="isCommon">
      <el-input
        v-model="editCustomerData.established_date"
        class="form-control-ml"
        placeholder="成立日期"
      ></el-input>
    </el-form-item>
    <el-form-item label="注册资本" v-if="isCommon">
      <el-input
        v-model="editCustomerData.register_funds"
        class="form-control-ml"
        placeholder="注册资本"
      ></el-input>
    </el-form-item>
    <el-form-item label="营业期限" v-if="isCommon">
      <el-input
        v-model="editCustomerData.bussiness_years"
        class="form-control-ml"
        placeholder="营业期限"
      ></el-input>
    </el-form-item>

    <el-form-item label="营业执照证件地址" v-if="isCommon">
      <el-input
        v-model="editCustomerData.cert_address"
        class="form-control-ml"
        placeholder="营业执照证件地址"
      ></el-input>
    </el-form-item>

    <el-form-item label="负责人" prop="corp_name" v-if="isCommon">
      <el-input
        v-model="editCustomerData.corp_name"
        class="form-control-ml"
        placeholder="请输入负责人名称"
      ></el-input>
    </el-form-item>
    <el-form-item :label="isCommon ? '负责人身份证' : '证件号码'" prop="lender_idcard">
      <el-input
        v-model="editCustomerData.lender_idcard"
        class="form-control-ml"
        placeholder="请输入身份证号"
      ></el-input>
    </el-form-item>
    <el-form-item label="身份证证件地址">
      <el-input
        v-model="editCustomerData.cert_address_corp"
        class="form-control-ml"
        placeholder="身份证证件地址"
      ></el-input>
    </el-form-item>
    <el-form-item label="联系电话" prop="mobile_no">
      <el-input
        v-model="editCustomerData.mobile_no"
        class="form-control-ml"
        placeholder="请输入联系电话"
      ></el-input>
    </el-form-item>
    <el-form-item label="经营范围">
      <el-input
        type="textarea"
        :rows="3"
        v-model="editCustomerData.business_scope"
        class="form-control-ml"
        placeholder="请输入经营范围"
      ></el-input>
    </el-form-item>
    <h4 class="form-title">贷款信息</h4>

    <el-form-item label="申请金额" prop="apply_funds">
      <el-input
        v-model="editCustomerData.apply_funds"
        class="form-control-ml"
        placeholder="请输入申请金额"
      >
        <span slot="append">万元</span>
      </el-input>
    </el-form-item>

    <el-form-item label="贷款年限" prop="load_years">
      <el-input
        v-model="editCustomerData.load_years"
        class="form-control-ml"
        placeholder="请输入贷款年限"
      >
        <span slot="append">年</span>
      </el-input>
    </el-form-item>

    <el-form-item label="贷款实际用途" prop="funds_use_dir">
      <el-input
        v-model="editCustomerData.funds_use_dir"
        class="form-control-ml"
        placeholder="请输入贷款实际用途"
      ></el-input>
    </el-form-item>
    <el-form-item label="是否有共同借款人">
      <el-radio-group v-model="editCustomerData.is_comm_loan">
        <el-radio label="1">是</el-radio>
        <el-radio label="0">否</el-radio>
      </el-radio-group>
    </el-form-item>
    <template v-if="+editCustomerData.is_comm_loan === 1">
      <el-form-item label="共同借款人">
        <el-button size="mini" @click="addPerson">
          <i class="fa fa-plus"></i>
          新增共同借款人
        </el-button>
        <table
          style="line-height: 1.2rem"
          class="table table-bordered table-sm bg-white table-vertical-middle text-center"
        >
          <colgroup>
            <col width="12%" />
            <col width="15%" />
            <col width="12%" />
            <col width="16%" />
            <col width="20%" />
            <col width="15%" />
            <col width="10%" />
          </colgroup>
          <tr>
            <td>类型</td>
            <td>主体名称</td>
            <td>法人名字</td>
            <td>联系电话</td>
            <td>证件号</td>
            <td>地址</td>
            <td>操作</td>
          </tr>
          <tr v-for="(p, index) of personData" :key="index">
            <td>{{ enumEntityType[p.com_person_type] }}</td>
            <td>{{ p.person_name }}</td>
            <td>{{ +p.com_person_type === 1 ? p.person_name_corp : '-' }}</td>
            <td>{{ p.person_phone }}</td>
            <td>{{ p.cert_no }}</td>
            <td>{{ p.person_address }}</td>
            <td>
              <el-button type="text" @click="addPerson(p, index)">
                <i class="fa fa-edit"></i>
              </el-button>
              <el-button type="text" @click="deletePerson(index)">
                <i class="fa fa-trash text-danger"></i>
              </el-button>
            </td>
          </tr>
          <tr v-if="!personData.length">
            <td colspan="7" class="text-muted">请先新增共同借款人</td>
          </tr>
        </table>
      </el-form-item>
    </template>

    <el-form-item>
      <el-button type="primary" :loading="saveLoading" class="btn-long" @click="submitForm">
        保存
      </el-button>
      <el-button :loading="saveLoading" class="btn-long" @click="beforeClose">取消</el-button>
    </el-form-item>

    <common-person
      :visible.sync="editCommonVisible"
      :form-data="editCommonForm"
      @back="setPerson"
      :attach="editPersonAttach"
    ></common-person>
  </el-form>
</template>

<script>
import { mapGetters } from 'vuex'
import { throttle } from '@vimi/utils-tool'
import SelectCustomerType from '@/components/select/SelectCustomerType'
import {
  getIdCard,
  getOrgInfo,
  ocrDateFormat,
  OCR_LICENSE_PERIOD_LONG,
} from '@/credit/views/city/program/ocr/index'
import SelectAddress from '@/components/select/SelectAddress'
import { idCardValidator, mobileValidator, registerNoValidator } from '@/common/plugins/validator'
import { addressFromLevel } from '@vimi/utils-tool'
import CommonPerson from '@/credit/views/city/program/ocr/CommonPerson'
import { uploadOss, deleteOss } from '@/common/api/oss'
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'
export default {
  components: {
    SelectAddress,
    SelectCustomerType,
    CommonPerson,
  },
  props: {
    queryId: String,
  },
  data() {
    const isNumberValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!Number.isFinite(+value)) {
        callback(new Error('请输入正确的数值'))
      } else {
        callback()
      }
    }
    return {
      enumEntityType,
      loading: false,
      isCommon: false,
      saveLoading: false,
      customerParams: {
        index: 1,
        size: 30,
        'submit_type.eq': 2,
        customer_name: '',
        address_code: '',
      },
      editCustomerData: {
        org_class: '',
        org_class_name: '',
        customer_name: '',
        customer_id: '',
        address_code: '',
        address_detail: '',
        register_no: '',
        established_date: '',
        register_funds: '',
        bussiness_years: '',
        cert_address: '',
        corp_name: '',
        lender_idcard: '',
        cert_address_corp: '',
        mobile_no: '',
        business_scope: '',
        apply_funds: '',
        load_years: '',
        funds_use_dir: '',
        is_comm_loan: '',
      },
      rules: {
        org_class: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
        customer_name: [
          { required: true, message: '请输入客户名称', trigger: 'blur' },
          { required: true, message: '请输入客户名称', trigger: 'change' },
        ],
        address_code: { required: true, message: '请选择经营地址', trigger: 'change' },
        register_no: [
          { required: true, message: '请输入营业执照号', trigger: 'blur' },
          {
            validator: registerNoValidator,
            message: '营业执照号格式错误',
            trigger: 'blur',
          },
        ],
        corp_name: { required: true, message: '请输入负责人名字', trigger: 'blur' },
        lender_idcard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: idCardValidator, message: '身份证号格式错误', trigger: 'blur' },
        ],
        mobile_no: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: mobileValidator, message: '手机号码错误', trigger: 'blur' },
        ],
        apply_funds: [
          { required: true, message: '请输入申请金额', trigger: 'blur' },
          { validator: isNumberValidator, trigger: 'blur' },
        ],
        load_years: [
          { required: true, message: '请输入贷款年限', trigger: 'blur' },
          { validator: isNumberValidator, trigger: 'blur' },
        ],
        funds_use_dir: { required: true, message: '请输入贷款用途', trigger: 'blur' },
      },
      imgData: [],
      registerList: [],
      deleteAttach: [],
      idImgFront: [],
      idImgBack: [],
      tableName: 'customer_related',
      attachTable: 'datum_customer_attachment',
      tableListName: 'comm_loan_person',
      tableData: {},
      addressLabel: '',
      topAddressLabel: '',
      mainPerson: {},
      personData: [],
      editPersonAttach: [],
      editIndex: '',
      editCommonForm: {},
      editCommonVisible: false,
      bolbUrl: {},
      commonOcr: {},
      attachs: {},
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'org']),
    dir() {
      return `credit/newProjec/${this.queryId || this.editCustomerData.lender_idcard}`
    },
    queryAddressCode() {
      return this.user.queryAddressCode
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.bolbUrl = {}
        this.commonOcr = {}
        this.personData = []
        this.mainPerson = {}
        this.deleteAttach = []
        if (this.queryId) {
          this.getData()
        } else {
          this.isFourModer = false
          this.tableData = {}
          this.idImgFront = []
          this.idImgBack = []
          this.registerList = []
          this.setCustomerData(this.tableData)
          this.initAttach([])
        }
      },
      immediate: true,
    },
  },
  created() {
    this.customerParams['service_id.eq'] = this.clientId
    this.getAddressData()
  },
  mounted() {},
  methods: {
    async getData() {
      // 通过传入的customer_related_id获取到客户信息
      const params = { 'customer_related_id.eq': this.queryId }
      this.loading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData('credit', this.tableName, params)
      )
      const [person, err1] = await this.$utils.promise(
        this.$api.getData('credit', this.tableListName, params)
      )
      const [attach, err2] = await this.getAttachMent()

      this.loading = false

      if (err || err1 || err2) {
        return this.$message.error('获取客户信息失败！')
      }
      const data = (res && res.data && res.data.length && res.data[0]) || {}
      const personData = person?.data ?? []
      this.mainPerson = personData.find(item => +item.is_main === 1) || {}
      this.personData = personData.filter(item => +item.is_main === 0)

      this.tableData = data
      this.setCustomerData(data)
      this.initAttach(attach.data ?? [])
    },
    getAttachMent() {
      return this.$utils.promise(
        this.$api.getData('credit', this.attachTable, {
          'customer_related_id.eq': this.queryId,
          'attachment_type.in': '身份证,营业执照',
        })
      )
    },
    initAttach(attach) {
      this.attachs = attach.reduce((ob, item) => {
        ob[item.lender_idcard] = [{ url: item.attachment, id: item.id }]
        return ob
      }, {})
      const customerIdCardFace = attach.find(
        item =>
          item.attachment_type === '身份证' &&
          item.attachment_type_code === 'face' &&
          item.lender_idcard === this.editCustomerData.lender_idcard
      )
      if (customerIdCardFace) {
        this.idImgFront = [{ url: customerIdCardFace.attachment, id: customerIdCardFace.id }]
      } else {
        this.idImgFront = []
      }
      const customerIdCardBack = attach.find(
        item =>
          item.attachment_type === '身份证' &&
          item.attachment_type_code === 'back' &&
          item.lender_idcard === this.editCustomerData.lender_idcard
      )
      if (customerIdCardBack) {
        this.idImgBack = [{ url: customerIdCardBack.attachment, id: customerIdCardBack.id }]
      } else {
        this.idImgBack = []
      }
      const customerRegitster = attach.find(
        item =>
          item.attachment_type === '营业执照' &&
          item.lender_idcard === this.editCustomerData.register_no
      )
      if (customerRegitster) {
        this.registerList = [{ url: customerRegitster.attachment, id: customerRegitster.id }]
      } else {
        this.registerList = []
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.saveLoading = true
          this.uploadCommonFile().finally(() => {
            this.saveLoading = false
            this.$refs.uploadFront.submit()
          })
        } else {
          this.$message.warning('填写的数据有误，请检查填写内容')
        }
      })
    },
    uploadCommonFile() {
      for (let key in this.bolbUrl) {
        URL.revokeObjectURL(this.bolbUrl[key][0].url)
      }
      this.imgData = []
      const uploadFiles = []
      const urls = []
      Object.keys(this.commonOcr).forEach(key => {
        if (this.attachs[key]) {
          this.deleteAttach.push(this.attachs[key]?.[0])
          urls.push(this.attachs[key]?.[0]?.url)
        }
        const data = this.personData.find(item => key === item.cert_no)
        if (data) {
          uploadFiles.push({
            com_person_type: data.com_person_type,
            cert_no: data.cert_no,
            file: this.commonOcr[data.cert_no],
            person_name: data.person_name,
          })
        }
      })
      if (!uploadFiles.length || +this.editCustomerData.is_comm_loan === 0) {
        return Promise.resolve({})
      }
      const promises = uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/newProjec/common/${it.cert_no}`,
          type: 0,
        })
      )
      return Promise.all(promises).then(list => {
        list.forEach((url, index) => {
          const { com_person_type, person_name, cert_no } = uploadFiles[index]
          const data = {
            attachment: url,
            parent_attachment_type: '立项附件',
            attachment_type: +com_person_type === 1 ? '营业执照' : '身份证',
            file_type: 1,
            attachment_type_code: 'face',
            lender_idcard: cert_no,
            remark: `共同借款人-${person_name}`,
          }
          if (this.queryId) {
            data.customer_related_id = this.queryId
          }
          this.imgData.push(data)
          this.commonOcr = {}
        })
        deleteOss(urls)
      })
    },
    setPerson(person, file) {
      this.commonOcr[person.cert_no] = file
      const url = file ? URL.createObjectURL(file) : ''
      if (this.bolbUrl[person.cert_no]) {
        URL.revokeObjectURL(this.bolbUrl[person.cert_no][0].url)
      }
      this.bolbUrl[person.cert_no] = [{ url: url }]
      if (this.editIndex === -1) {
        this.personData.push(person)
      } else {
        this.personData[this.editIndex] = { ...person }
      }
    },
    deletePerson(index) {
      if (this.personData.length < 2) {
        return this.$message.warning('最少需添加一个共同借款人')
      }
      this.personData.splice(index, 1)
    },
    addPerson(row = {}, index = -1) {
      if (row.cert_no) {
        this.editPersonAttach = this.bolbUrl[row.cert_no] || this.attachs[row.cert_no] || []
      } else {
        this.editPersonAttach = []
      }
      this.editCommonVisible = true
      this.editCommonForm = { ...row }
      this.editIndex = index
    },
    linkto() {
      window.open('http://www.gsxt.gov.cn/index.html')
    },
    getAddressData() {
      const address = new Set()

      address.add(addressFromLevel(this.queryAddressCode, 1))
      address.add(addressFromLevel(this.queryAddressCode, 2))
      address.add(addressFromLevel(this.queryAddressCode, 3))
      if (!this.queryAddressCode) {
        this.topAddressLabel = ''
        return
      }
      this.$api
        .getData(
          'industrial_db',
          'geo_codings',
          {
            'orWhere.id.eq': [...address],
          },
          { region_lever: 'asc' }
        )
        .then(res => {
          const data = res?.data ?? []
          this.topAddressLabel = data.map(item => item.geo_name).join('')
        })
    },
    getAddress(label) {
      this.addressLabel = label || ''
    },
    throttleGetData: throttle(500, function (queryString, cb) {
      this.getCustomer(queryString, cb)
    }),
    async getCustomer(queryString = '', cb) {
      queryString = queryString.trim()
      let data = []

      if (this.customerParams.customer_name === queryString) {
        cb(data)
        return
      }

      this.customerParams.customer_name = queryString
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', 'datum_customer_info_warehouse', this.customerParams)
      )

      if (res && res.data) {
        data = res.data.data || []
      }

      cb(data)
    },
    handleSelectFarm(customer) {
      this.setCustomerData(customer)
    },
    setCustomerData(customer) {
      Object.keys(this.editCustomerData).forEach(key => {
        this.editCustomerData[key] = customer[key] || ''
      })
      this.editCustomerData.lender_idcard = customer.id_card || customer.lender_idcard
      if (!this.editCustomerData.is_comm_loan) {
        this.editCustomerData.is_comm_loan = '0'
      }
      this.isCommon = +customer.customer_type === 1
      this.tableData.address = customer.address || ''

      this.$nextTick(() => {
        this.$refs.form?.clearValidate()
      })
    },
    clearId() {
      if (this.queryId) {
        return
      }
      this.editCustomerData.customer_id = ''
    },
    registerChange(file) {
      if (!file || !file.raw) {
        return
      }
      const fileData = file.raw
      this.loading = true
      getOrgInfo(fileData)
        .then(res => {
          const data = res?.data ?? {}
          this.editCustomerData.register_no = data.reg_num || ''
          this.editCustomerData.corp_name = data.person
          this.editCustomerData.customer_name = data.name
          this.editCustomerData.cert_address = data.address
          this.editCustomerData.business_scope = data.business
          this.editCustomerData.register_funds = data.capital
          this.editCustomerData.established_date = ocrDateFormat(data.establish_date)
          this.editCustomerData.bussiness_years =
            data.valid_period === OCR_LICENSE_PERIOD_LONG
              ? '长期'
              : `${this.editCustomerData.established_date}至${ocrDateFormat(data.valid_period)}`
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleUploadRegister(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.registerList?.[0] || {}
      this.handleUploadAttach(
        img,
        fileUrl,
        '营业执照',
        true,
        this.editCustomerData.register_no,
        `营业执照-${this.editCustomerData.customer_name}`
      )
      this.onSubmit()
    },
    handleUploadAttach(img, fileUrl, type = '身份证', isFase = true, id, fileName = '') {
      if (img.url && img.url !== fileUrl.url) {
        const data = {
          attachment: img.url,
          attachment_type: type,
          parent_attachment_type: '立项附件',
          attachment_type_code: isFase ? 'face' : 'back',
          lender_idcard: id,
          remark: fileName || img.name,
        }
        if (this.queryId) {
          data.customer_related_id = this.queryId
        }
        this.imgData.push(data)
        if (fileUrl.id) {
          this.deleteAttach.push(fileUrl)
        }
      }
    },
    async idImgFrontChange(file) {
      if (!file || !file.raw) {
        return
      }
      const fileData = file.raw
      this.loading = true
      getIdCard(fileData, true)
        .then(res => {
          const data = res?.data ?? {}
          this.editCustomerData.lender_idcard = data.num || ''
          this.editCustomerData.corp_name = data.name
          this.editCustomerData.cert_address_corp = data.address
          if (!this.isCommon) {
            this.editCustomerData.customer_name = data.name
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleUploadFront(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.idImgFront?.[0] || {}
      const name = this.isCommon
        ? `身份证(头像页)-${this.editCustomerData.corp_name}`
        : `身份证(头像页)-${this.editCustomerData.customer_name}`
      this.handleUploadAttach(
        img,
        fileUrl,
        '身份证',
        true,
        this.editCustomerData.lender_idcard,
        name
      )
      this.$refs.uploadBack.submit()
    },
    handleUploadBack(images) {
      const img = images?.[images.length - 1] || {}
      const fileUrl = this.idImgBack?.[0] || {}
      const name = this.isCommon
        ? `身份证(国徽页)-${this.editCustomerData.corp_name}`
        : `身份证(国徽页)-${this.editCustomerData.customer_name}`
      this.handleUploadAttach(
        img,
        fileUrl,
        '身份证',
        false,
        this.editCustomerData.lender_idcard,
        name
      )
      this.$refs.uploadRegister.submit()
    },
    onSubmit() {
      const { editCustomerData } = this
      const data = {
        customer_name: editCustomerData.customer_name?.replace(/\s*/g, ''),
        corp_name: this.isCommon
          ? editCustomerData.corp_name?.replace(/\s*/g, '')
          : editCustomerData.customer_name?.replace(/\s*/g, ''),
        customer_type: this.isCommon ? 1 : 2,
        mobile_no: editCustomerData.mobile_no,
        address_code: editCustomerData.address_code,
        address_detail: editCustomerData.address_detail,
        register_no: this.isCommon ? editCustomerData.register_no : '',
        org_class: editCustomerData.org_class,
        org_class_name: editCustomerData.org_class_name,
        lender_idcard: editCustomerData.lender_idcard,
        business_scope: editCustomerData.business_scope,
        submit_type: 2,
        apply_funds: editCustomerData.apply_funds,
        load_years: editCustomerData.load_years,
        funds_use_dir: editCustomerData.funds_use_dir,
        channel_type: 0,
        recommend_status: 1,
        is_comm_loan: editCustomerData.is_comm_loan,
        cert_address: editCustomerData.cert_address,
        cert_address_corp: editCustomerData.cert_address_corp,
        register_funds: editCustomerData.register_funds,
        established_date: editCustomerData.established_date,
        bussiness_years: editCustomerData.bussiness_years,
      }
      data.service_id = this.clientId
      data.service_name = this.org.orgName
      if (editCustomerData.customer_id) {
        data.customer_id = editCustomerData.customer_id
      }
      if (+this.editCustomerData.is_comm_loan === 1 && this.personData.length < 1) {
        return this.$message.error('至少输入一个共同借款主体')
      }

      let personData = []
      if (+this.editCustomerData.is_comm_loan === 1) {
        personData = [...this.personData]
      }
      const mainPerson = {
        com_person_type: this.isCommon ? 1 : 2,
        person_name: this.editCustomerData.customer_name,
        person_phone: this.editCustomerData.mobile_no,
        is_main: 1,
        cert_no: this.isCommon
          ? this.editCustomerData.register_no
          : this.editCustomerData.lender_idcard,
        person_address: this.addressLabel
          ? this.addressLabel + this.editCustomerData.address_detail
          : this.tableData.address,
      }

      if (this.mainPerson.id) {
        mainPerson.id = this.mainPerson.id
      }
      personData.push(mainPerson)

      if (this.queryId) {
        data.customer_related_id = this.queryId
      } else {
        data.submit_person_name = this.user.realName
        data.submit_client_id = this.clientId
        data.submit_client_name = this.org.orgName
      }

      const addformData = {
        masterTableInfo: JSON.stringify(data),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(personData),
        slaveTableName: this.tableListName,
        slaveTableName1: this.attachTable,
        slaveTableInfo1: JSON.stringify(this.imgData),
      }
      const updateformData = {
        masterTableInfo: JSON.stringify(data),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(personData),
        slaveTableName: this.tableListName,
      }

      if (!this.queryId) {
        this.addFarm(addformData)
      } else {
        // 修改需传所有附件不然会删除，所以单独添加附件
        this.updateFarm(updateformData)
        this.submitAttachment()
      }
    },
    updateFarm(data) {
      this.saveLoading = true
      this.$api
        .relatedUpdate(this.$serviceName, data)
        .then(() => {
          this.$message.success('操作成功！')
          this.handleSuccess()
          this.getData()
          this.deleteAttachMent()
        })
        .catch(err => {
          if (err) {
            const errStr =
              typeof err.data?.error_description === 'string'
                ? err.data?.error_description
                : '操作失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    deleteAttachMent() {
      if (!this.deleteAttach.length) {
        return
      }
      const ids = this.deleteAttach.map(item => item.id).join(',')
      // 组件自带删除fileList oss文件
      // const urls = this.deleteAttach.map(item => item.url)
      this.$api.deleteData(this.$serviceName, this.attachTable, ids)
      // deleteOss(urls)
      this.deleteAttach = []
    },
    submitAttachment() {
      if (this.imgData.length > 0) {
        this.$api.addBatch('credit', 'datum_customer_attachment', this.imgData).catch(err => {
          this.$message.error(err?.data?.error_description || '附件保存失败，请重试！')
        })
      }
    },
    addFarm(data) {
      this.saveLoading = true
      this.$api
        .relatedBatch(this.$serviceName, data)
        .then(() => {
          this.$message.success('添加客户成功！')
          this.handleSuccess()
        })
        .catch(err => {
          if (err) {
            const errStr =
              typeof err.data?.error_description === 'string'
                ? err.data?.error_description
                : '添加客户失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    handleSuccess() {
      this.bolbUrl = {}
      this.commonOcr = {}
      this.idImgFront = []
      this.idImgBack = []
      this.registerList = []
      this.$emit('success', true)
      this.$emit('close', false)
      this.tableData = {}
      this.setCustomerData(this.tableData)
    },
    beforeClose() {
      this.setCustomerData(this.tableData)
      this.addressLabel = ''
      this.$emit('close', false)
    },
    handleOrgClassSelect(val, item) {
      if (!item) return
      this.isCommon = +item.customerType === 1
      this.editCustomerData.org_class_name = item.orgClassName
    },
  },
}
</script>

<style lang="scss" scoped></style>
